package main

import (
	"context"
	"log"

	"github.com/bytedance/sonic"
	"github.com/hibiken/asynq"
)

type emailPayload struct {
	UserID int
}

func main() {
	srv := asynq.NewServer(
		asynq.RedisClusterClientOpt{
			Addrs: []string{
				"192.168.0.138:6379",
				"192.168.0.143:6379",
				"192.168.0.140:6379",
				"192.168.0.142:6379",
				"192.168.0.141:6379",
				"192.168.0.139:6379",
			},
		},
		asynq.Config{
			Concurrency: 10,
			Queues: map[string]int{
				"high":    10,
				"default": 5,
				"low":     1,
			},
		},
	)

	mux := asynq.NewServeMux()
	mux.HandleFunc("email:welcome", sendWelcomeEmail)
	mux.HandleFunc("email:reminder", sendReminderEmail)
	mux.HandleFunc("email:ad", sendAdEmail)

	if err := srv.Run(mux); err != nil {
		log.Fatal(err)
	}

	log.Println("app exited")
}

func sendWelcomeEmail(ctx context.Context, task *asynq.Task) error {
	var p any
	if err := sonic.Unmarshal(task.Payload(), &p); err != nil {
		log.Printf("could not unmarshal payload: %v", err)
		return err
	}
	log.Printf("sending welcome email: %#v", p)

	return nil
}

func sendReminderEmail(ctx context.Context, task *asynq.Task) error {
	var p any
	if err := sonic.Unmarshal(task.Payload(), &p); err != nil {
		log.Printf("could not unmarshal payload: %v", err)
		return err
	}
	log.Printf("sending email reminder: %+v", p)

	return nil
}

func sendAdEmail(ctx context.Context, task *asynq.Task) error {
	var p any
	if err := sonic.Unmarshal(task.Payload(), &p); err != nil {
		log.Printf("could not unmarshal payload: %v", err)
		return err
	}
	log.Printf("sending email ad: %#v", p)
	return nil
}
